package com.manage.action.interceptor;

import java.util.ArrayList;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.opensymphony.xwork2.util.TextParseUtil;

public class PrivilegeInterceptor implements Interceptor {
	volatile private static ArrayList<String> privilege;
	//  索引 1 2 3 表示是否赋予设备管理（增删改）权限
	//  索引 4 5 6 表示是否赋予房间管理（增删改）权限
	private String includeActionName;
	 
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		String actionName =	invocation.getProxy().getActionName();
		Set<String> set = TextParseUtil.commaDelimitedStringToSet(includeActionName);
		if(!set.contains(actionName)){
			return invocation.invoke();
		}
		
		Map session=invocation.getInvocationContext().getSession();
		String  role=""+session.get("role"); //1 超级管理员  2助管
		if("1".equals(role)){  //超级管理员的一切Action都不拦截
			return invocation.invoke();
		}else{
			if(privilege!=null && privilege.contains(actionName ) ){
					return invocation.invoke();
			}else{
				
				HttpServletResponse response = ServletActionContext
						.getResponse();
				response.setContentType("text/html;charset=UTF-8");
				response.setHeader("Pragma", "No-cache");
				response.setHeader("Cache-Control", "no-cache");
				response.setDateHeader("Expires", 0);
				response.getWriter().write("{\"statusCode\":\"300\",\"message\":\"对不起，您暂时没有权限\"," +
						"\"callbackType\":\"closeCurrent\"}");
				
				response.getWriter().flush();
				return null;
			}
		}
	}
	
	@Override
	public void init() {
		privilege=new ArrayList<String>();
	}

	@Override
	public void destroy() {
		privilege=null;
	}

	public String getIncludeActionName() {
		return includeActionName;
	}

	public void setIncludeActionName(String includeActionName) {
		this.includeActionName = includeActionName;
	}

	public static ArrayList<String> getPrivilege() {
		return privilege;
	}

	public static void setPrivilege(ArrayList<String> privilege) {
		PrivilegeInterceptor.privilege = privilege;
	}


	
}
